<?php 
class candidateAddAction extends AdminMaster{
	public function execute($request){
		switch ($this->data['action']) {
			case 'get':
				$this->data['candidate_id'] = $request->getParameter('id', 0);
				$ex_ids = CandidateToExportsTable::getListByCandidateId($this->data['candidate_id']);
				$ids_not = array();
				foreach($ex_ids as $exi){
					if(!in_array($exi['export_id'], $ids_not)){
						$ids_not[] = $exi['export_id'];
					}
				}
				$this->data['exports'] = ExportsTable::getDataList(array('filter_ids_not' => $ids_not), null);
				$this->setTemplate('candidateGet');
				$this->setVar('data', $this->data);
				return sfView::SUCCESS;
				break;
			case 'add':
				$candidate_id = $request->getParameter('candidate_id', -1);
				$export_id 	= $request->getParameter('export_id', -1);
				if(intval($candidate_id) > 0 && intval($export_id) > 0){
					if( !CandidateToExportsTable::isAdded($candidate_id, $export_id)){
						if (CandidateToExportsTable::insert(array('candidate_id' => $candidate_id, 'export_id' => $export_id))){
							echo __('add_export_success', null, 'candidate_candidates');
							return sfView::NONE;
						}
					}
				}
				echo __('add_export_fail', null, 'candidate_candidates');
				#return sfView::NONE;
				break;
			case 'new':
				$candidate_id = $request->getParameter('candidate_id', -1);
				$export_name = $request->getParameter('txtExport', '');
				if(intval($candidate_id) >0 && !empty($export_name)){
					$export_id = ExportsTable::insert(array('name' => $export_name, 'description' => ''));
					if (intval($export_id) > 0){
						if (CandidateToExportsTable::insert(array('candidate_id' => $candidate_id, 'export_id' => $export_id))){
							echo __('add_export_success', null, 'candidate_candidates');
							return sfView::NONE;
						}
					}
				}
				echo __('add_export_fail', null, 'candidate_candidates');
				#return sfView::NONE;
				break;
			case 'export':
				$export_id = $request->getParameter('id', -1);
				$export = ExportsTable::getDataById($export_id);
				$arr = CandidateToExportsTable::getListByExportId($export_id);
				$ids = array();
				foreach($arr as $id){
					if(!in_array($id['candidate_id'], $ids)){
						$ids[] = $id['candidate_id'];
					}
				}
				$candidates = CandidatesTable::getDataList(array('filter_ids_in' => $ids), null);
				$ex = new PHPExcel ();
				$ex->getProperties ()
					->setCreator ( sfConfig::get ( 'app_excel_creator' ) )
					->setLastModifiedBy ( sfConfig::get ( 'app_excel_creator' ) )
					->setTitle ( sfConfig::get ( 'app_excel_candidate-title' ) )
					->setSubject ( sfConfig::get ( 'app_excel_candidate-title' ) )
					->setDescription ( sfConfig::get ( 'app_excel_candidate-title' ) );
				$ex->setActiveSheetIndex ( 0 )
					->setTitle ( sfConfig::get ( 'app_excel_candidate-title' ) );
				
				$ex->getActiveSheet ()
					->setCellValue ( 'A1',  'Full name/ Họ tên')
					->setCellValue ( 'B1',  'Date of birth/ Ngày sinh (yyyy/mm/dd' )
					->setCellValue ( 'C1',  'Gender/ Giới tính' )
					->setCellValue ( 'D1',  'Education level/ Trình độ' )
					->setCellValue ( 'E1',  'Professional/ Chuyên ngành' )
					->setCellValue ( 'F1',  'Address/ Địa chỉ' )
					->setCellValue ( 'G1',  'Mobile phone/ Điện thoại' )
					->setCellValue ( 'H1',  'Email' );
				
				$count_i = 1;
				foreach ( $candidates as $can ) {
					$mTmp = MasterMajorsTable::getDataListByCandidateId($can['id']);
					$major = '';
					$sj = '';
					foreach($mTmp as $mj){
						$major.= $sj.$mj['name'];
						$sj = ', ';
					}
					$city = LocationCitiesTable::getDataById($can['location_city_id']);
					$dist = LocationDistrictsTable::getDataById($can['location_district_id']);
					$addr = $can['address']. (empty($dist['name'])? '':(', '. $dist['name'])) . (empty($city['name'])?'': (', '. $city['name']));
					//print_r($can); die;
					$gender = 'Không xác định';
					if(intval($can['gender']) == 1){
						$gender = 'Male / Nam';
					}elseif(intval($can['gender']) == 2){
						$gender = 'Female / Nữ';
					}
					
					$count_i ++;
					$ex->getActiveSheet ()
					->setCellValue ( 'A' . $count_i, $can['full_name'] )
					->setCellValue ( 'B' . $count_i, DateHelper::dateFormatFree ( $can ['date_of_birth'], 'Y-m-d' ) )
					->setCellValue ( 'C' . $count_i, $gender)
					->setCellValue ( 'D' . $count_i, $can['education'] )
					->setCellValue ( 'E' . $count_i, $major )
					->setCellValue ( 'F' . $count_i, $addr )
					->setCellValue ( 'G' . $count_i, $can['phone_number'] )
					->setCellValue ( 'H' . $count_i, $can['email']);
					
				}
				
				$exIO = PHPExcel_IOFactory::createWriter ( $ex, 'CSV' );
				ob_end_clean ();
					
				header ( 'Content-Type: text/csv' );
				header ( 'Content-Disposition: attachment;filename="' . UserStringHelper::titleToAddress($export['name']) . '.' . date ( 'Y-m-d', time () ) . '.csv"' );
				header ( 'Cache-Control: max-age=0' );
				print "\xEF\xBB\xBF";
				$exIO->save ( 'php://output' );
				#return sfView::NONE;
				break;
			case 'export-advance':
				$session = $request->getParameter('arr_value', '');
				$id = $request->getParameter('id', -1);
				if($session == '' || intval($id) <= 0 ){
					print_r(__('export-error', null, 'export_exports'));
				}else{
					$this->getUser()->setFlash('export', $session);
					$this->getUser()->setFlash('id', $id);
					print_r('<a onclick="$.fancybox.close();" href="'.sfConfig::get('app_prefix').$this->generateUrl('candidate_add_export', array('action_name' => 'export-session')).'" target="_blank">'.__('export-getfile', null, 'export_exports').'</a>');
				}
				break;
			case 'export-session':
				$export_id = $this->getUser()->getFlash('id', -1);
				$export = ExportsTable::getDataById($export_id);
				$arr = CandidateToExportsTable::getListByExportId($export_id);
				$ids = array();
				foreach($arr as $id){
					if(!in_array($id['candidate_id'], $ids)){
						$ids[] = $id['candidate_id'];
					}
				}
				$candidates = CandidatesTable::getDataList(array('filter_ids_in' => $ids), null);
				$ex = new PHPExcel ();
				$ex->getProperties ()
				->setCreator ( sfConfig::get ( 'app_excel_creator' ) )
				->setLastModifiedBy ( sfConfig::get ( 'app_excel_creator' ) )
				->setTitle ( sfConfig::get ( 'app_excel_candidate-title' ) )
				->setSubject ( sfConfig::get ( 'app_excel_candidate-title' ) )
				->setDescription ( sfConfig::get ( 'app_excel_candidate-title' ) );
				$ex->setActiveSheetIndex ( 0 )
				->setTitle ( sfConfig::get ( 'app_excel_candidate-title' ) );
				
				#ADD FIELD TO EXPORT
				$arr_attr = $this->getUser()->getFlash('export', '');
				$arr_attr = explode(',', $arr_attr);
				$char = 'A';
				foreach ($arr_attr as $attr){
					switch ($attr){
						case 'source':
							$ex->getActiveSheet ()
							->setCellValue ( $char.'1',  'Source/ Nguồn');
							break;
						case 'fullname':
							$ex->getActiveSheet ()
							->setCellValue ( $char.'1',  'Full name/ Họ tên');
							break;
						case 'idcard':
							$ex->getActiveSheet ()
							->setCellValue ( $char.'1',  'ID Card/ CMND');
							break;
						case 'gender':
							$ex->getActiveSheet ()
							->setCellValue ( $char.'1',  'Gender/ Giới tính' );
							break;
						case 'birthday':
							$ex->getActiveSheet ()
							->setCellValue ( $char.'1',  'Date of birth/ Ngày sinh (yyyy/mm/dd)' );
							break;
						case 'married':
							$ex->getActiveSheet ()
							->setCellValue ( $char.'1',  'Married/ TT Hôn Nhân');
							break;
						case 'job_hope':
								$ex->getActiveSheet ()
								->setCellValue ( $char.'1',  'The job was wanna work/ Công việc mong muốn');
								break;
						case 'private':
							$ex->getActiveSheet ()
							->setCellValue ( $char.'1',  'Private/ Đặc điểm riêng');
							break;
						case 'current_address':
							$ex->getActiveSheet ()
							->setCellValue ( $char.'1',  'Current address/ Địa chỉ liên lạc' );
							break;
						case 'home_address':
							$ex->getActiveSheet ()
							->setCellValue ( $char.'1',  'Holder address/ Hộ khẩu');
							break;
						case 'email':
							$ex->getActiveSheet ()
							->setCellValue ( $char.'1',  'Email' );
							break;
						case 'phone_number':
							$ex->getActiveSheet ()
							->setCellValue ( $char.'1',  'Mobile phone/ Điện thoại' );
							break;
						case 'education':
							$ex->getActiveSheet ()
							->setCellValue ( $char.'1',  'Education level/ Trình độ' );
							break;
						case 'education_history':
							$ex->getActiveSheet ()
							->setCellValue ( $char.'1',  'Education history/ Quá trình học tập');
							break;
						case 'major':
							$ex->getActiveSheet ()
							->setCellValue ( $char.'1',  'Professional/ Chuyên ngành' );
							break;
						case 'language':
							$ex->getActiveSheet ()
							->setCellValue ( $char.'1',  'Foreign languages/ Ngoại ngữ');
							break;
						case 'it':
							$ex->getActiveSheet ()
							->setCellValue ( $char.'1',  'IT/ CNTT');
							break;
						case 'other_major':
							$ex->getActiveSheet ()
							->setCellValue ( $char.'1',  'Other major/ Bằng cấp khác');
							break;
						case 'salary':
							$ex->getActiveSheet ()
							->setCellValue ( $char.'1',  'Salary (hope)/ Lương mong muốn');
							break;
						case 'working_status':
							$ex->getActiveSheet ()
							->setCellValue ($char.'1',  'Working status/ TT Công việc');
							break;
						case 'working_history':
							$ex->getActiveSheet ()
							->setCellValue ( $char.'1',  'Working history/ Quá trình làm việc');
							break;
						case 'remark':
							$ex->getActiveSheet ()
							->setCellValue ( $char.'1',  'Remark (basic)/ Đánh giá');
							break;
					}
					$char++;
				}
				
				
				$count_i = 1;
				foreach ( $candidates as $can ) {
					$count_i ++;
					$char = 'A';
					foreach ($arr_attr as $attr){
						switch ($attr){
							case 'source':
								$rs = CandidateResourcesTable::getDataById($can['resource_id']);
								$ex->getActiveSheet ()
								->setCellValue ( $char.$count_i,  $rs['name']);
								break;
							case 'fullname':
								$ex->getActiveSheet ()
								->setCellValue ( $char.$count_i, $can['full_name']);
								break;
							case 'idcard':
								$ex->getActiveSheet ()
								->setCellValue ( $char.$count_i,  $can['identity_card']);
								break;
							case 'gender':
								$gender = 'None/ Không xác định';
								if(intval($can['gender']) == 1){
									$gender = 'Male / Nam';
								}elseif(intval($can['gender']) == 2){
									$gender = 'Female / Nữ';
								}
								$ex->getActiveSheet ()
								->setCellValue ( $char.$count_i,  $gender );
								break;
							case 'birthday':
								$ex->getActiveSheet ()
								->setCellValue ( $char.$count_i,  DateHelper::dateFormatFree ( $can ['date_of_birth'], 'Y-m-d' ));
								break;
							case 'married':
								
								$ex->getActiveSheet ()
								->setCellValue ( $char.$count_i,  intval($can['is_married']) == 1? 'Yes/ Có' : '-');
								break;
							case 'job_hope':
									$ex->getActiveSheet ()
									->setCellValue ( $char.$count_i,  $can['job_hope']);
									break;
							case 'private':
								$pr = CandidatePrivatesTable::getDataList(array('filter_candidate_id' => $can['id']), null, null);
								$prtext = '';
								$spa = '';
								foreach($pr as $p){
									$prtext.= $spa. $p['private_name'];
									$spa = ', ';
								}
								$ex->getActiveSheet ()
								->setCellValue ( $char.$count_i,  $prtext);
								break;
							case 'current_address':
								$city = LocationCitiesTable::getDataById($can['location_city_id']);
								$dist = LocationDistrictsTable::getDataById($can['location_district_id']);
								$addr = $can['address']. (empty($dist['name'])? '':(', '. $dist['name'])) . (empty($city['name'])?'': (', '. $city['name']));
								$ex->getActiveSheet ()
								->setCellValue ( $char.$count_i,  $addr );
								break;
							case 'home_address':
								$ex->getActiveSheet ()
								->setCellValue ( $char.$count_i,  $can['home_address']);
								break;
							case 'email':
								$ex->getActiveSheet ()
								->setCellValue ( $char.$count_i,  $can['email'] );
								break;
							case 'phone_number':
								$ex->getActiveSheet ()
								->setCellValue ( $char.$count_i,  $can['phone_number'] );
								break;
							case 'education':
								$ex->getActiveSheet ()
								->setCellValue ( $char.$count_i,  $can['education']  );
								break;
							case 'education_history':
								$eh = CandidateEducationsTable::getDataList(array('filter_candidate_id' => $can['id']), null, null);
								$prtext = '';
								$spa = '';
								foreach($eh as $e){
									$lv = MasterEducationLevelsTable::getDataById($e['education_level_id']);
									$prtext.= $spa. $e['education_school'].' - '. $e['major_subject']. ' - '. $lv['name'];
									$spa = ', ';
								}
								$ex->getActiveSheet ()
								->setCellValue ( $char.$count_i,  $prtext);
								break;
							case 'major':
								$mTmp = MasterMajorsTable::getDataListByCandidateId($can['id']);
								$major = '';
								$sj = '';
								foreach($mTmp as $mj){
									$major.= $sj.$mj['name'];
									$sj = ', ';
								}
								$ex->getActiveSheet ()
								->setCellValue ( $char.$count_i,  $major );
								break;
							case 'language':
								$cl = CandidateToForeignLanguagesTable::getListByCandidateId($can['id']);
								$txt = '';
								$sj = '';
								foreach($cl as $l){
									$lang = MasterForeignLanguagesTable::getDataById($l['foreign_language_id']);
									$level = MasterForeignLanguageLevelsTable::getDataById($l['foreign_language_level_id']);
									$txt.= $sj.$lang['language_name'].' - '. $level['name'];
									$sj = ', ';
								}
								
								$ex->getActiveSheet ()
								->setCellValue ( $char.$count_i,  $txt);
								break;
							case 'it':
								$it = CandidateToInformationTechnologiesTable::getListByCandidateId($can['id']);
								$txt = '';
								$sj = '';
								foreach($it as $t){
									$int = MasterInformationTechnologiesTable::getDataById($t['information_technology_id']);
									$intlevel = MasterInformationTechnologyLevelsTable::getDataById($t['information_technology_level_id']);
									$txt.= $sj.$int['name'].' - '. $intlevel['name'];
									$sj = ', ';
								}
								$ex->getActiveSheet ()
								->setCellValue ( $char.$count_i,  $txt);
								break;
							case 'other_major':
								$sk = CandidateOtherSkillesTable::getListByCandidateId($can['id']);
								$txt = '';
								$sj = '';
								foreach($sk as $s){
									$txt.= $sj.$s['skill'];
									$sj = ', ';
								}
								$ex->getActiveSheet ()
								->setCellValue ( $char.$count_i,  $txt);
								break;
							case 'salary':
								$sa = MasterSalariesTable::getDataById($can['salary_id']);
								$sText = 'Discuss/ Thoả thuận';
								if(intval($sa['salary_from']) > 0 ){
									$sText = $sa['salary_from']. ' - '. $sa['salary_to'];
								}
								$ex->getActiveSheet ()
								->setCellValue ( $char.$count_i,  $sText);
								break;
							case 'working_status':
								$text = 'None/ Không xác định';
								switch ($can['working_status']){
									case '0':
										$text = 'Finding job/ Đang tìm việc';
										break;
									case '1':
										$text = 'Waiting review/ Chờ phỏng vấn';
										break;
									case '2':
										$text = 'On working/ Đã có việc làm';
										break;
								}
								$ex->getActiveSheet ()
								->setCellValue ($char.$count_i, $text);
								break;
							case 'working_history':
								$work = CandidateWorkingHistoriesTable::getDataList(array('filter_candidate_id' => $can['id']), null, null);
								$txt = '';
								$sj = '';
								foreach($work as $w){
									$pos = CompanyPersonContactPositionsTable::getDataById($w['position_id']);
									$txt.= $sj.$pos['name'] . ' - ' . $w['company_name'];
									$sj = ', ';
								}
								$ex->getActiveSheet ()
								->setCellValue ( $char.$count_i,  $txt);
								break;
							case 'remark':
								$ex->getActiveSheet ()
								->setCellValue ( $char.$count_i,  $can['remark']);
								break;
						}
						$char++;
					}
				}
				
				$exIO = PHPExcel_IOFactory::createWriter ( $ex, 'CSV' );
				ob_end_clean ();
					
				header ( 'Content-Type: text/csv' );
				header ( 'Content-Disposition: attachment;filename="' . UserStringHelper::titleToAddress($export['name']) . '.' . date ( 'Y-m-d', time () ) . '.csv"' );
				header ( 'Cache-Control: max-age=0' );
				print "\xEF\xBB\xBF";
				$exIO->save ( 'php://output' );
				break;
		}
		return sfView::NONE;
	}
}